import type { AxiosRequestConfig } from 'axios';

import type { AjaxResult, RequestOptions } from '#/request';

/**
 * 流式请求工具类，复用现有的axios拦截器逻辑
 */
import { h } from 'vue';

import {
  cloneDeep,
  isArray,
  isBoolean,
  isEmpty,
  isNull,
  isNumber,
  isObject,
  isString,
  isUndefined,
} from '@eacloud/utils';

import { ContentTypeEnum, RequestEnum } from '@/enums/httpEnum';
import { useGlobSetting } from '@/hooks/setting';
import { useI18n } from '@/hooks/web/useI18n';
import { useMessage } from '@/hooks/web/useMessage';
import { useErrorLogStoreWithOut } from '@/store/modules/errorLog';
import { useIdentityStoreWithOut } from '@/store/modules/identity';
import { useLocaleStoreWithOut } from '@/store/modules/locale';
import { deepMerge } from '@/utils';
import { formatToDateTime } from '@/utils/date';
import { stringify } from 'qs';

import { formatRequestDate, formatToken, joinQuery, joinTimestamp } from '../helper';

const globSetting = useGlobSetting();

/** 流式请求参数 */
export interface StreamRequestOptions extends RequestOptions {
  /** 是否携带认证token */
  withToken?: boolean;
  /** 请求是否携带身份凭证（如 Cookie、HTTP 认证等）
   * include - 总是发送凭证（包括跨域请求）、omit - 从不发送任何凭证、same-origin - 仅在同源请求时发送凭证
   */
  credentials?: 'include' | 'omit' | 'same-origin';
  // /** 错误消息模式 */
  // errorMessageMode?: 'message' | 'modal' | 'none';
}

/** 流式请求配置 */
export interface StreamRequestConfig extends Omit<AxiosRequestConfig, 'responseType'> {
  /** 身份验证键 */
  authenticationKey?: string;
  /** 身份验证方案 */
  authenticationScheme?: string;
  /** 请求参数 */
  requestOptions?: RequestOptions;
  /** 流式数据处理回调 */
  onChunk?: (chunk: string) => void;
  /** 流式请求完成回调 */
  onEnd?: () => void;
  /** 流式请求错误回调 */
  onError?: (error: any) => void;
  /** 流式请求开始回调 */
  onStart?: () => void;
}

/**
 * 流式请求客户端
 * 基于fetch API实现，复用axios的拦截器逻辑  1_800_000
 */
export class StreamRequestClient {
  private readonly config: StreamRequestConfig;

  constructor(config: StreamRequestConfig) {
    this.config = config;
  }

  /**
   * GET流式请求
   */
  async get<T = AjaxResult>(config?: Omit<StreamRequestConfig, 'method'>, options?: StreamRequestOptions) {
    return this.request<T>(
      {
        ...config,
        method: 'GET',
      },
      options,
    );
  }

  /**
   * POST流式请求
   */
  async post<T = AjaxResult>(config?: Omit<StreamRequestConfig, 'method'>, options?: StreamRequestOptions) {
    return this.request<T>(
      {
        ...config,
        method: 'POST',
      },
      options,
    );
  }

  /**
   * 执行流式请求
   */
  async request<T = AjaxResult>(config: StreamRequestConfig, options?: StreamRequestOptions) {
    const { requestOptions: _requestOptions, ...thisConfig } = this.config;
    let conf: StreamRequestConfig = Object.assign({}, thisConfig, cloneDeep(config));

    // cancelToken 如果被深拷贝，会导致最外层无法使用cancel方法来取消请求
    if (config.cancelToken) {
      conf.cancelToken = config.cancelToken;
    }
    if (config.signal) {
      conf.signal = config.signal;
    }

    const opt: RequestOptions = Object.assign({}, _requestOptions, options, { provider: 'stream' });

    conf = this.beforeRequestHook(conf, opt);
    conf.requestOptions = opt;
    conf = this.supportFormData(conf);

    const requestInit = this.beforeRequestHandler(conf, conf.requestOptions!);

    conf.onStart?.();
    try {
      const response = await fetch(conf.url!, requestInit);

      if (!response.ok) {
        await this.catchHandler(response, conf, conf.requestOptions!);
        return;
      }

      if (!response.body) {
        throw new Error('Response body is null');
      }

      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let buffer = '';

      try {
        while (true) {
          const { done, value } = await reader.read();

          if (done) {
            // 处理缓冲区中剩余的数据
            if (buffer.trim()) {
              conf.onChunk?.(buffer);
            }
            break;
          }

          // 解码数据块
          const chunk = decoder.decode(value, { stream: true });
          buffer += chunk;

          // 按行分割数据（适用于SSE格式）
          const lines = buffer.split('\n');
          buffer = lines.pop() || ''; // 保留最后一个不完整的行

          for (const line of lines) {
            if (line.trim()) {
              // 处理SSE格式的数据
              if (line.startsWith('data: ')) {
                const data = line.slice(6);
                if (data !== '[DONE]') {
                  conf.onChunk?.(data);
                }
              } else {
                // 处理普通文本数据
                conf.onChunk?.(line);
              }
            }
          }
        }

        conf.onEnd?.();
      } finally {
        reader.releaseLock();
      }

      return (await this.transformResponseHandler(response, conf)) as T;
    } catch (error: any) {
      conf.onError?.(error);
      throw error;
    }
  }

  /** 支持表单数据 support form-data */
  supportFormData(config: AxiosRequestConfig) {
    const headers = config.headers || this.config.headers;
    const contentType = headers?.['Content-Type'] || headers?.['content-type'];

    if (
      contentType !== ContentTypeEnum.FORM_URLENCODED ||
      !Reflect.has(config, 'data') ||
      config?.method?.toUpperCase() === RequestEnum.GET
    ) {
      return config;
    }

    return {
      ...config,
      data: stringify(config.data, { arrayFormat: 'brackets' }),
    };
  }

  /** 请求之前处理器 */
  private beforeRequestHandler(config: StreamRequestConfig, options: StreamRequestOptions): RequestInit {
    const headers: Record<string, string> = {
      // 'Content-Type': 'application/json',
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      Connection: 'keep-alive',
      ...(config.headers as any),
    };

    const identityStore = useIdentityStoreWithOut();
    // 请求之前处理config
    const accessToken = identityStore.getAccessToken;
    if (accessToken && options?.withToken !== false) {
      const authenticationKey = config.authenticationKey!;
      const authenticationScheme = config.authenticationScheme!;
      (config as Recordable).headers[authenticationKey] = formatToken(accessToken, authenticationScheme);
    }
    // 请求的语言-后端配合
    const localeStore = useLocaleStoreWithOut();
    const locale = localeStore.getLocale;
    if (locale) {
      headers['Accept-Language'] = locale;
    }
    // 请求的时区-后端配合
    const date = new Date();
    const offsetMinutes = date.getTimezoneOffset(); // 本地时间与 GMT 之间的差值，单位是分钟，正值表示本地时间比 GMT 慢，负值表示本地时间比 GMT 快。
    const offsetHours = -offsetMinutes / 60; // 转换为小时
    headers['Time-Zone'] = offsetHours.toString();
    headers['Time-Stamp'] = formatToDateTime(date, 'YYYY-MM-DD HH:mm:ssZ');
    // 请求的平台-后端配合
    headers.platform = import.meta.env.VITE_GLOB_APP_NAMESPACE;

    return {
      method: config.method || 'POST',
      headers,
      body: config.data ? JSON.stringify(config.data) : undefined,
      signal: config?.timeout ? AbortSignal.timeout(config?.timeout) : undefined,
      credentials: options?.credentials,
    };
  }
  /** 请求之前处理config */
  private beforeRequestHook(config: StreamRequestConfig, options: StreamRequestOptions) {
    const { apiUrl, joinPrefix, joinParamsToUrl, formatDate, joinTime = true, urlPrefix } = options || {};

    if (joinPrefix && urlPrefix && isString(urlPrefix)) {
      config.url = `${urlPrefix}${config.url}`;
    }

    if (apiUrl && isString(apiUrl)) {
      config.url = `${apiUrl}${config.url}`;
    }
    const params = config.params || {};
    const data = config.data || false;
    formatDate && data && !isString(data) && formatRequestDate(data);
    if (config?.method?.toUpperCase() === RequestEnum.GET) {
      if (!isString(params)) {
        // 给 get 请求加上时间戳参数，避免从缓存中拿数据。
        config.params = Object.assign(params || {}, joinTimestamp(joinTime, false));
      } else {
        // 兼容restful风格
        config.url = joinQuery(config.url || '', `${params.replace(/&$/, '')}&${joinTimestamp(joinTime, true)}`);
        config.params = undefined;
      }
    } else {
      if (!isString(params)) {
        formatDate && formatRequestDate(params);
        if (
          Reflect.has(config, 'data') &&
          config.data &&
          (Object.keys(config.data).length > 0 || config.data instanceof FormData)
        ) {
          config.data = data;
          config.params = params;
        } else {
          // 非GET请求如果没有提供data，则将params视为data
          config.data = params;
          config.params = undefined;
        }
        if (joinParamsToUrl) {
          config.url = joinQuery(config.url || '', Object.assign({}, config.params, config.data));
        }
      } else {
        // 兼容restful风格
        config.url = joinQuery(config.url || '', params);
        config.params = undefined;
      }
    }
    return config;
  }

  /** 异常处理器 */
  private async catchHandler(res: Response, config: StreamRequestConfig, options: StreamRequestOptions) {
    const { t } = useI18n();
    const { createMessage, createErrorModal } = useMessage();

    const errorData = await res.text();
    let errorObj: any;
    try {
      errorObj = JSON.parse(errorData);
    } catch {
      errorObj = { msg: errorData, code: res.status };
    }
    const error = new Error(errorObj.msg || 'Request failed') as any;
    (error as any).response = {
      data: errorObj,
      ...res,
    };
    (error as any).code = errorObj.code || res.status;

    const errorLogStore = useErrorLogStoreWithOut();
    errorLogStore.addAjaxErrorInfo(error);

    const { response, code, message } = error || {};
    const errorMessageMode = options?.errorMessageMode || 'none';
    const msg: string = response?.data?.error?.message?.toString?.() || message?.toString?.() || '';
    const err: string = error?.toString?.() ?? '';

    // 如果响应状态码为 401，说明访问令牌无效或过期。此时，会尝试使用 refreshToken 请求新的 accessToken。成功后，更新 store 中的 accessToken 并重新发起之前失败的请求。
    const icUnauthorized = options?.icUnauthorized ?? true;
    if (icUnauthorized && error?.response?.status === 401 && !(config as any)._retry) {
      (config as any)._retry = true;
      const identityStore = useIdentityStoreWithOut();
      const token = identityStore.getToken;
      const refreshToken = token?.RefreshToken;
      if (refreshToken) {
        // 尝试使用刷新令牌获取新的访问令牌
        await identityStore.refreshToken(refreshToken, 'none');
        // 重新发起之前失败的请求
        return await this.request(config, options);
      }
    }

    let errMessage = '';
    if (code === 'ECONNABORTED' && msg.indexOf('timeout') !== -1) {
      errMessage = t('sys.api.apiTimeoutMessage');
    } else if (err?.includes('Network Error')) {
      errMessage = t('sys.api.networkExceptionMsg');
    } else if (err?.toLowerCase()?.includes('abort')) {
      errMessage = t('sys.api.operationAbort');
    }
    if (errMessage) {
      if (errorMessageMode === 'modal') {
        createErrorModal({
          zIndex: 999999999,
          title: () => h('span', t('sys.api.errorTip')),
          content: () => h('span', errMessage),
        });
      } else if (errorMessageMode === 'message') {
        createMessage.error(errMessage);
      }
    }

    throw error;
  }

  /** 响应数据处理器。如果数据不是预期格式，可直接抛出错误。 */
  private async transformResponseHandler(response: Response, config: StreamRequestConfig) {
    const { t } = useI18n();
    const { createMessage, createSuccessModal } = useMessage();
    const { requestOptions: options = {} } = config;
    const { isTransformResponse, isReturnNativeResponse } = options;
    // 是否返回原生响应头 比如：需要获取响应头时使用该属性
    if (isReturnNativeResponse) {
      return response;
    }
    // 不进行任何处理，直接返回
    // 用于页面代码可能需要直接获取code，data，message这些信息时开启
    const result = await response.json();
    if (!isTransformResponse) {
      return result;
    }
    // 错误的时候返回
    if (result === undefined) {
      // return '[HTTP] Request has no return value';
      throw new Error(t('sys.api.requestHasNoReturnValue'));
    }
    // 返回值为空，直接返回。
    if (!result) {
      return result;
    }
    // 非后台统一的字段类型，直接返回。
    if (
      !(
        isObject(result) &&
        !isArray(result) &&
        Reflect.has(result, 'Type') &&
        Reflect.has(result, 'Content') &&
        Reflect.has(result, 'Data') &&
        Reflect.has(result, 'Succeeded') &&
        Reflect.has(result, 'Failed') &&
        isNumber(result?.Type) &&
        isBoolean(result?.Succeeded) &&
        isBoolean(result?.Failed)
      )
    ) {
      return result;
    }
    // 这里 Type，Content，Data，Succeeded，Failed 为后台统一的字段，需要在 types.ts 内修改为项目自己的接口返回格式
    const { Content, Succeeded } = result;

    // 这里逻辑可以根据项目进行修改
    // const hasSuccess = result && Reflect.has(result, 'Type') && Type === ResultStatusEnum.Success;
    const hasSuccess = Succeeded;
    if (hasSuccess) {
      let successMsg = Content;

      if (isNull(successMsg) || isUndefined(successMsg) || isEmpty(successMsg)) {
        successMsg = t(`sys.api.successMessage`);
      }

      if (options.successMessageMode === 'modal') {
        createSuccessModal({
          zIndex: 999999999,
          title: () => h('span', t('sys.api.successTip')),
          content: () => h('span', successMsg),
        });
      } else if (options.successMessageMode === 'message') {
        createMessage.success(successMsg);
      }
      return result;
    }

    // 重组异常返回信息
    const res = Object.assign({}, response, {
      /**  代码 */
      code: result?.Type || response.status,
      /**  消息 */
      message: result?.Content || response.statusText,
      /**  响应结果 */
      response,
    });
    throw res || t('sys.api.requestError');
  }
}

export function createStreamRequest(opt?: Partial<StreamRequestConfig>) {
  return new StreamRequestClient(
    // 深度合并
    deepMerge(
      {
        /** 身份验证键 */
        authenticationKey: globSetting.authenticationKey ?? 'Authorization',
        /** 身份验证方案
         *  ，See https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#authentication_schemes
         *  ，authentication schemes，e.g: Bearer
         */
        authenticationScheme: globSetting.authenticationScheme ?? 'Bearer',
        /** 超时时间 */
        timeout: 1800 * 1000,
        /** 请求头 */
        headers: {
          'Content-Type': 'text/event-stream',
          'Cache-Control': 'no-cache',
          Connection: 'keep-alive',
        },
        /** 请求配置项，可以在独立的接口请求中覆盖。 */
        requestOptions: {
          /** 基础接口地址 */
          apiUrl: globSetting.apiUrl,
          /** 添加前缀 */
          joinPrefix: true,
          /** 地址前缀 */
          urlPrefix: globSetting.urlPrefix,
          /** 是否返回原生响应头 比如：需要获取响应头时使用该属性。 */
          isReturnNativeResponse: false,
          /** 需要对返回数据进行处理 */
          isTransformResponse: true,
          /** post请求的时候添加参数到url */
          joinParamsToUrl: false,
          /** 格式化提交参数时间 */
          formatDate: true,
          /** 消息提示类型 */
          errorMessageMode: 'message',
          /** 是否加入时间戳 */
          joinTime: true,
          /** 忽略重复请求 */
          ignoreCancelToken: true,
          /** 是否携带token */
          withToken: true,
          /** 重试请求 */
          retryRequest: {
            /** 开启重试 */
            isOpenRetry: true,
            /** 重试方法，保险起见默认只开启GET请求 */
            methods: [RequestEnum.GET],
            /** 重试次数 */
            count: 5,
            /** 重试等待时长(ms) */
            waitTime: 100,
          },
          /** 启用401拦截：当返回401时，将尝试刷新token后再进行请求，如果依然返回401，将执行登出等逻辑。 */
          icUnauthorized: true,
        },
      },
      opt || {},
    ),
  );
}

/**
 * 默认流式请求实例
 */
export const streamRequest = createStreamRequest();

// /** 自定义流式请求实例 */
// export const otherStreamRequest = createStreamRequest({
//   requestOptions: {
//     joinPrefix: true,
//     urlPrefix: '/xxx',
//   },
// });
